import { WorksItem } from '@/pages/pc/components/Works';
import CheckTag from '@/pages/pc/components/CheckTag';
import Pagination from '@/pages/pc/components/Pagination';
import styles from './index.less';
import { useState, useEffect, useRef } from 'react';
import { Link, useHistory, Helmet } from 'umi';
import { allGet } from '@/services/pc';
import qs from 'qs';
import Empty from '@/pages/pc/components/Empty';
import VideoPlayerModal from '../components/VideoPlayer';
import { message, Select, Skeleton } from 'antd';
import WorkDetailModal, { WorkDetailModalRef } from '@/pages/pc/components/WorkDetailModal';

const score = [
  { label: '全部', value: '' },
  { label: 'S', value: '4' },
  { label: 'A+', value: '3' },
  // { label: 'A', value: '2' },
  // { label: 'B', value: '1' },
];
const order = [
  { label: '最新', value: 'bid' },
  { label: '推荐', value: 'rand' },
];

const pageSize = 20;
const Index = (props) => {
  const { query = {}, search, match } = props;
  const history = useHistory();
  const workDetailModalRef = useRef<WorkDetailModalRef>(null);
  useEffect(() => {
    if (props.initialPropsOk) {
      // setLoading(false);
    }
  }, [props.initialPropsOk]);

  // 客户端同步
  useEffect(() => {
    if (!props.isServer) {
      // setData(props.data ?? []);
    }
  }, [props.initialPropsOk, props.isServer]);

  const handleChangeSearch = (key, value) => {
    const newQuery = query;
    newQuery[key] = value?.[0];
    const string = qs.stringify(query);

    history.push(`/center/detail/works/${1}?${string}`);
  };
  const itemRender = (current, type, originalElement) => {
    if (type === 'page') {
      return <Link to={`/center/detail/works/${current}${search}`}>{current}</Link>;
    }
    if (type === 'next') {
      return <Link to={`/center/detail/works/${current}${search}`}>{originalElement}</Link>;
    }
    if (type === 'prev') {
      return <Link to={`/center/detail/works/${current}${search}`}>{originalElement}</Link>;
    }

    return originalElement;
  };
  const handleItemClick = (index, e) => {
    workDetailModalRef.current?.show({
      ids: props?.works?.data?.list?.map((item) => item.bid),
      currentId: props?.works?.data?.list?.[index]?.bid,
    });
    // VideoPlayerModal.showStar({
    //   data:
    //     props?.works?.data?.list?.map((item) => ({ ...item, url: item.video || item.pic })) || [],
    //   defaultIndex: index,
    // });
  };

  const currentPage = parseInt(match?.params?.page);
  const handleDeleteOK = (item) => {
    message.success('删除成功');
    const newQuery = { ...query, t: Date.now() };
    const string = qs.stringify(newQuery);
    history.push(`/center/detail/works/${currentPage}?${string}`);
  };

  const handleBackClass = () => {
    history.push(`/center/courses/detail/${query.classid}`);
  };
  return (
    <div className={styles.page}>
      <div className={styles.pathtitle}>
        <span className={styles.classname} onClick={handleBackClass}>
          {query.classname}
        </span>
        <span className={styles.arrow}>{'>'}</span>
        <span className={styles.pathcurrent}>学员作业</span>
      </div>
      <div className={styles.wrapper}>
        <div className={styles.header}>
          <div className={styles.row}>
            <div className={styles.rowitem}>
              <div className={styles.key}>排序：</div>
              <CheckTag
                data={order}
                key={query.order}
                defaultValue={[query.order || '']}
                onChange={(value) => handleChangeSearch('order', value)}
              />
            </div>
            <div className={styles.rowitem}>
              <div className={styles.key}>评级：</div>
              <Select
                className={styles.select}
                options={score}
                key={query.score}
                defaultValue={query.score || ''}
                onChange={(value) => handleChangeSearch('score', value)}
              />
            </div>
          </div>
        </div>
        <div className={styles.main}>
          <div className={styles.list}>
            {props?.works?.data?.list?.length > 0 ? (
              props?.works?.data?.list?.map((item, index) => (
                <div key={item.bid} className={styles.item}>
                  <WorksItem
                    onClick={handleItemClick}
                    isLink={false}
                    hasAdminAction
                    itemType={4}
                    type={item.video ? 'video' : 'img'}
                    index={index}
                    handleDeleteOK={handleDeleteOK}
                    {...item}
                  />
                </div>
              ))
            ) : props.initialPropsOk ? (
              <Empty />
            ) : (
              <div
                style={{
                  display: 'grid',
                  width: '100%',
                  gridTemplateColumns: '1fr 1fr 1fr 1fr',
                  gap: 20,
                }}
              >
                {new Array(20).fill(1).map((num, index) => (
                  <Skeleton key={index + num} active />
                ))}
              </div>
            )}
          </div>
        </div>
        {(props?.works?.data?.count > pageSize || currentPage != 1) && (
          <Pagination
            pageSize={pageSize}
            itemRender={itemRender}
            className={styles.pagination}
            total={props?.works?.data?.count}
            current={currentPage}
          />
        )}
      </div>
      <WorkDetailModal ref={workDetailModalRef} />
    </div>
  );
};
Index.getInitialProps = async ({ match, history, isServer }) => {
  const { query, search } = history?.location || {};

  const params: any = {
    mod: 'busywork',
    do: 'list',
    perpage: pageSize,
    page: match?.params?.page,
    version: 'pc1.0',
  };
  if (query.classid) {
    params.classid = query.classid;
  }
  if (query.order) {
    params.order = query.order;
  }
  if (query.score) {
    params.score = query.score;
  }
  // const [works, columnResponse] = await Promise.all([
  //   allGet({ params }),
  //   allGet({
  //     params: { mod: 'course', do: 'category', version: 'pc1.0' },
  //   }),
  // ]);
  // const keywords = (columnResponse.data?.map?.((item) => item.name + '作品') || []).join(',');
  // const description = (
  //   works?.data?.list?.map?.((item) => item.username + '作品：' + item.classname) || []
  // )
  //   .join(',')
  //   .slice(0, 100);

  const [works] = await Promise.all([allGet({ params })]);
  return {
    initialPropsOk: true,
    works,
    match,
    query,
    search,
    isServer,
    // keywords,
    // description,
  };
};
export default Index;
